using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using WebRole1.DataService;
using System.Data.Objects;

namespace WebRole1.Config
{
   public partial class Category : System.Web.UI.Page
   {
      static DateTime PersistCookie = DateTime.Now.AddYears(10);
      const string LoginCookie = "webauthtoken";

      protected void Page_Load(object sender, EventArgs e)
      {
         if (!Page.IsPostBack)
         {
            FillPlaceholder();

            //EntityDataSource1.Where = "";
            HttpCookie lastPageCookie = new HttpCookie("LastPage");
            lastPageCookie.Value = "Config/Category.aspx";
            lastPageCookie.Expires = PersistCookie;
            Response.Cookies.Add(lastPageCookie);
         }
      }

      private void FillPlaceholder()
      {
         using (LocationsDBEntities locEntities = new LocationsDBEntities())
         {
            string userId = Utils.GetUserFromCookie();

            if (!string.IsNullOrEmpty(userId))
            {
               UserTbl user = Utils.GetCurrentUser(locEntities, userId);
               user.Category.Load();

               PlaceHolderCatgories.Controls.Add(new LiteralControl("<p><a href='#' onclick=\"PublishCategoryByName('','','');return false;\">Add a new City Link</a></p>"));
               PlaceHolderCatgories.Controls.Add(new LiteralControl("<p>Modify my city links:</p><ul>"));

               foreach (WebRole1.DataService.Category cat in user.Category.OrderBy(f => f.CategoryName))
               {
                  if (cat.CityReference.EntityKey == null)
                  {
                     continue;
                  }
                  string linkControl = String.Format("<li><a href='#' onclick=\"ModifyCat({0}, '', '');\">{1} ({2})</a> </li>\n",
                           cat.CategoryID, cat.CategoryName, cat.CategoryShortName);
                  PlaceHolderCatgories.Controls.Add(new LiteralControl(linkControl));
               }
               PlaceHolderCatgories.Controls.Add(new LiteralControl("</ul>"));
            }
            else
            {
               PlaceHolderCatgories.Controls.Add(new LiteralControl("Please login use your Windows Live ID.  Only login users can add new city links and modify the city links that created by the same user."));
            }
         }
      }

      public UserTbl GetCurrentUser(LocationsDBEntities locEntities)
      {
         string userId = "";
         Label mpLabel = (Label)Master.FindControl("LabelCurrentLiveUser");
         if (mpLabel != null)
         {
            userId = mpLabel.Text;
         }

         return Utils.GetCurrentUser(locEntities, userId);
      }

      protected void ButtonDelete_Click(object sender, EventArgs e)
      {
         if (String.IsNullOrEmpty(TextBoxCategoryID.Text.Trim()))
         {
            throw new Exception("Must specify a link to delete");
         }
         using (LocationsDBEntities locEntities = new LocationsDBEntities())
         {
            int catID=0;
            string existingID = TextBoxCategoryID.Text.Trim();
            if (!string.IsNullOrEmpty(existingID))
            {
               catID = Convert.ToInt32(existingID);
            }
            if (catID == 0)
            {
               throw new Exception("Link ID cannot be 0");
            }

            UserTbl user = GetCurrentUser(locEntities);
            WebRole1.DataService.Category myCat = null;
            
            myCat = locEntities.Category.First(f => f.CategoryID == catID);

            myCat.UserTblReference.Load();
            if (myCat.UserTbl.UserID != user.UserID)
            {
               throw new Exception("Only user published this category can delete it.");
            }

            locEntities.DeleteObject(myCat);
            locEntities.SaveChanges();
         }
         FillPlaceholder();
      }

      protected void ButtonPublish_Click(object sender, EventArgs e)
      {
         if (String.IsNullOrEmpty(TextBoxCategoryName.Text.Trim()))
         {
            throw new Exception("Must specify a link name");
         }
         if (String.IsNullOrEmpty(TextBoxCategoryShortName.Text.Trim()))
         {
            throw new Exception("Must specify a short name");
         }

         string urlType = TextBoxCategorySvcUrlType.Text.Trim();
         if (!String.IsNullOrEmpty(urlType))
         {
            if (urlType != "ogdi" && urlType != "kml" && urlType != "georss" && urlType != "csv")
            {
               throw new Exception("urlType must be empty, or one of the following: ogdi, kml, georss, csv");
            }
         }

         using (LocationsDBEntities locEntities = new LocationsDBEntities())
         {
            if (String.IsNullOrEmpty(TextBoxParentCategoryID.Text.Trim()))
            {
               //We always give the id 0 as parent Id is it's not specified
               TextBoxParentCategoryID.Text = "0";
            }

            int catID = 0;
            string existingID = TextBoxCategoryID.Text.Trim();
            if (!string.IsNullOrEmpty(existingID))
            {
               catID = Convert.ToInt32(existingID);
            }

            string citySearchName = TextBoxSearchCity.Text.Trim();
            City city = null;

            if (!String.IsNullOrEmpty(citySearchName))
            {
               city = locEntities.City.First(f => f.SearchName == citySearchName);
            }

            UserTbl user = GetCurrentUser(locEntities);
            WebRole1.DataService.Category myCat = null;

            if (catID == 0)
            {
               myCat = new WebRole1.DataService.Category();
               myCat.CreateTime = DateTime.Now;
               myCat.UserTbl = user;
            }
            else
            {
               myCat = locEntities.Category.First(f => f.CategoryID == catID);

               myCat.UserTblReference.Load();
               if (myCat.UserTbl.UserID != user.UserID)
               {
                  throw new Exception("Only user published this category can modify it.");
               }
            }

            myCat.CategoryName = TextBoxCategoryName.Text.Trim();
            myCat.CategoryDescription = TextBoxCategoryDesc.Text.Trim();
            myCat.CategoryShortName = TextBoxCategoryShortName.Text.Trim();
            myCat.CategorySvcUrl = TextBoxCategorySvcUrl.Text.Trim();
            myCat.CategorySvcUrlType = TextBoxCategorySvcUrlType.Text.Trim();
            myCat.ParentID = Convert.ToInt32(TextBoxParentCategoryID.Text.Trim());
            myCat.MapIconUrl = TextBoxMapIconUrl.Text.Trim();
            myCat.City = city;

            if (catID == 0)
            {
               locEntities.AddToCategory(myCat);
            }
            locEntities.SaveChanges();
         }

         FillPlaceholder();
      }

   }
}
